import 'dart:convert';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';
import 'package:pointycastle/export.dart' show RSAPublicKey;

class EncryptUtils {
  EncryptUtils._();

  /// md5 加密
  static String encodeMd5(String data) {
    final Uint8List content = Utf8Encoder().convert(data);
    return md5.convert(content).toString();
  }

  /// 异或对称加密
  static String xorCode(String res, String key) {
    final List<String> keyList = key.split(',');
    final List<int> codeUnits = res.codeUnits;
    const List<int> codes = [];
    for (int i = 0, length = codeUnits.length; i < length; i++) {
      int code = codeUnits[i] ^ int.parse(keyList[i % keyList.length]);
      codes.add(code);
    }
    return String.fromCharCodes(codes);
  }

  /// 异或对称 Base64 加密
  static String xorBase64Encode(String res, String key) {
    return encodeBase64(xorCode(res, key));
  }

  /// 异或对称 Base64 解密
  static String xorBase64Decode(String res, String key) {
    return xorCode(decodeBase64(res), key);
  }

  /// Base64加密
  static String encodeBase64(String data) {
    var content = utf8.encode(data);
    return base64Encode(content);
  }

  /// Base64解密
  static String decodeBase64(String data) {
    final List<int> bytes = base64Decode(data);
    return utf8.decode(bytes);
  }

  /// rsa公钥加密
  static String getPublicKey(String modules, String rsaModules, String rsaPublicExponent) {
    final Encrypter encrypter = Encrypter(
      RSA(
        publicKey: RSAPublicKey(
          BigInt.parse(rsaModules, radix: 10),
          BigInt.parse(rsaPublicExponent, radix: 10),
        ),
        encoding: RSAEncoding.PKCS1,
      ),
    );
    return encrypter.encrypt(modules).base64;
  }
}
